package tech.mobi.child.utils;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SharedPreferencesUtil {
	private final static String NAME = "iMobile";
	public final static String HOME_COUNT_KEY = "homeCount";
	private final static String HOME_NAME = "home_";

	public static void setString(Context context,String key,String value){
		SharedPreferences sharedPreferences = context.getSharedPreferences(NAME,Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString(key, value);
		editor.commit();
	}
	/**
	 * 
	 * @param context
	 * @param key
	 * @return 如果没有，返回空字符串
	 */
	public static String getString(Context context,String key){
		SharedPreferences sharedPreferences = context.getSharedPreferences(NAME,Context.MODE_PRIVATE);
		return sharedPreferences.getString(key, "");
		
	}
	/**
	 * 保存HomeAct的ListView的数据，每一项的格式：“title，icon，class”
	 * @param context
	 * @param data
	 */
	public static void setHomeByString(Context context,ArrayList<HashMap<String, String>> data){
		int size = data.size();
		setString(context, HOME_COUNT_KEY, size+"");
		for (int i=0;i<size;i++) {
			HashMap<String, String> map = data.get(i);
			StringBuilder sb = new StringBuilder();
			sb.append(map.get("title"));
			sb.append(",");
			sb.append(map.get("icon"));
			sb.append(",");
			sb.append(map.get("class"));
			setString(context, HOME_NAME+(i+1), sb.toString());
		}
	}
	/**
	 * 获取HomeAct的ListView的数据
	 * @param context
	 * @return
	 */
	public static ArrayList<HashMap<String, String>> getHomeList(Context context){
		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
		String homeCountStr = SharedPreferencesUtil.getString(context, SharedPreferencesUtil.HOME_COUNT_KEY);
		if(!"".equals(homeCountStr)){
			int homeCount = Integer.parseInt(homeCountStr) ;
			if(homeCount!=0){
				for(int i=1;i<=homeCount;i++){
					String str = SharedPreferencesUtil.getString(context, HOME_NAME+i);
					String[] strs = str.split(",");
					HashMap<String, String> map = new HashMap<String, String>();

					map.put("title", strs[0]);
					map.put("icon", strs[1]);
					map.put("class", strs[2]);
					data.add(map);
				}
			}
		}
		return data;
	}
	/**
	 * 在HomeAct中是否存在要添加的Home
	 * @param context
	 * @param hashMap
	 * @return
	 */
	public static boolean isHasHome(Context context,HashMap<String, String> hashMap) {
		boolean b = true;
		String homeCountStr = getString(context, HOME_COUNT_KEY);
		if("".equals(homeCountStr)||"0".equals(homeCountStr)){
			b = false;
		}else{
			ArrayList<HashMap<String, String>> list = getHomeList(context);
			int size = list.size();
			for(int i=0;i<size;i++){
				if(list.get(i).equals(hashMap)){
					b = true;
					break;
				}else{
					b = false;
				}
			}
		}
		return b;
	}
}
